package com.xuan.yubi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;

public class MultipleConsumer {

    private static final String MULTI_QUEUE_NAME = "multi_queue";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        final Connection connection = factory.newConnection();
        final Channel channel1 = connection.createChannel();
        final Channel channel2 = connection.createChannel();

        channel1.queueDeclare(MULTI_QUEUE_NAME, true, false, false, null);
        channel2.queueDeclare(MULTI_QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        channel1.basicQos(1);
        channel2.basicQos(1);

        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            try {
                // doWork(message);
                System.out.println(" [x] Received '" + message + "'");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                System.out.println(" [x] Done");
                channel1.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            try {
                // doWork(message);
                System.out.println(" [x] Received '" + message + "'");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                System.out.println(" [x] Done");
                channel2.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        channel1.basicConsume(MULTI_QUEUE_NAME, false, deliverCallback1, consumerTag -> { });
        channel2.basicConsume(MULTI_QUEUE_NAME, false, deliverCallback2, consumerTag -> { });
    }
}